package com.fary.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fary.base.BaseApiService;
import com.fary.base.BaseResponse;
import com.fary.constants.Constants;
import com.fary.core.bean.MeiteBeanUtils;
import com.fary.core.utils.MD5Util;
import com.fary.member.feign.VerifiedCodeServiceFeign;
import com.fary.member.input.dto.UserInputDTO;
import com.fary.member.mapper.UserMapper;
import com.fary.member.mapper.entity.UserDo;
import com.fary.member.service.api.MemberRegisterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MemberRegisterServiceImpl extends BaseApiService<JSONObject> implements MemberRegisterService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VerifiedCodeServiceFeign verifiedCodeServiceFeign;

    @Transactional
    public BaseResponse<JSONObject> register(@RequestBody UserInputDTO userInputDTO, String registCode) {
        String mobile = userInputDTO.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return setResultError("手机号码不能为空!");
        }
        String password = userInputDTO.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空!");
        }
        // 2.验证码注册码是否正确 暂时省略 会员调用微信接口实现注册码验证
        BaseResponse<JSONObject> verifiedWeixinCode = verifiedCodeServiceFeign.verifiedWeixinCode(mobile, registCode);
        if (!verifiedWeixinCode.getCode().equals(Constants.HTTP_RES_CODE_200)) {
            return setResultError(verifiedWeixinCode.getMsg());
        }
        // 3.对用户的密码进行加密 // MD5 可以解密 暴力破解
        userInputDTO.setPassword(MD5Util.MD5(password));
        // 4.调用数据库插入数据
        UserDo userDo = MeiteBeanUtils.dtoToDo(userInputDTO, UserDo.class);
        return userMapper.register(userDo) > 0 ? setResultSuccess("注册成功") : setResultError("注册失败!");
    }
}
